﻿using System;
using System.Collections.Generic;
using System.Data;

namespace ZeBobo5.LibraryHelper.Core.Sql
{
    public sealed class SqlContext
    {
        private static Dictionary<string, IDbConnection> _connections;

        public static void AddConnection(string connectionName, IDbConnection connection)
        {
            if (_connections == null)
            {
                _connections = new Dictionary<string, IDbConnection>();
            }
            _connections[connectionName] = connection;
        }

        public static void CloseConnection(string connectionName)
        {
            if (_connections != null && _connections[connectionName] != null)
            {
                _connections[connectionName].Close();
            }
        }

        public static void CloseAllConnections()
        {
            foreach (IDbConnection connection in _connections.Values)
            {
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }
                connection.Dispose();
            }
        }

        public static IDbConnection GetConnection(string connectionName)
        {
            if (_connections != null && _connections[connectionName] != null)
            {
                return _connections[connectionName];
            }
            throw new Exception("Connection not found.");
        }

        public static bool CouldConnectToDataBase(string connectionName)
        {
            return CouldConnectToDataBase(connectionName, false);
        }

        public static bool CouldConnectToDataBase(string connectionName, bool closeConnection)
        {
            try
            {
                if (GetConnection(connectionName).State != ConnectionState.Open)
                {
                    GetConnection(connectionName).Open();
                    if (closeConnection)
                    {
                        GetConnection(connectionName).Close();
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}